package com.haoyeteng.sxbd.modular.business.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.haoyeteng.sxbd.core.base.controller.BaseController;
import com.haoyeteng.sxbd.core.base.model.ResponseResult;
import com.haoyeteng.sxbd.core.common.annotion.Permission;
import com.haoyeteng.sxbd.core.common.constant.factory.ConstantFactory;
import com.haoyeteng.sxbd.core.common.constant.factory.PageFactory;
import com.haoyeteng.sxbd.core.log.LogObjectHolder;
import com.haoyeteng.sxbd.core.util.DateUtil;
import com.haoyeteng.sxbd.core.util.ExportExcelUtils;
import com.haoyeteng.sxbd.core.util.ToolUtil;
import com.haoyeteng.sxbd.modular.business.model.Address;
import com.haoyeteng.sxbd.modular.business.model.Bill;
import com.haoyeteng.sxbd.modular.business.model.Order;
import com.haoyeteng.sxbd.modular.business.service.IAddressService;
import com.haoyeteng.sxbd.modular.business.service.IBillService;
import com.haoyeteng.sxbd.modular.business.service.IOrderService;
import com.haoyeteng.sxbd.modular.business.warpper.BillWarpper;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.*;

/**
 * 发票控制器
 *
 * @author haoyeteng
 * @Date 2019-05-31 10:35:42
 */
@Controller
@RequestMapping("/bill")
public class BillController extends BaseController {

    private String PREFIX = "/business/bill/";

    @Autowired
    private IBillService billService;
    
    @Autowired
    private  IAddressService addressService;
    
    @Autowired
    private IOrderService orderService;

    /**
     * 跳转到发票首页
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "bill.html";
    }

    /**
     * 跳转到添加发票
     */
    @RequestMapping("/bill_add")
    public String billAdd() {
        return PREFIX + "bill_add.html";
    }

    /**
     * 跳转到修改发票
     */
    @RequestMapping("/bill_update/{billId}")
    public String billUpdate(@PathVariable Integer billId, Model model) {
        Bill bill = billService.selectById(billId);
        model.addAttribute("item",bill);
        LogObjectHolder.me().set(bill);
        return PREFIX + "bill_edit.html";
    }

    /**
     * 获取发票列表
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    @Permission
    public ResponseResult<Object> list(Integer billType,Integer billState,String orderId,String startTime,String endTime) {
    	ResponseResult<Object> result = new ResponseResult<Object>();
    	Page<Bill> page = new PageFactory<Bill>().defaultPage();
        List<Map<String, Object>> billList=billService.selectBillList(page, billType, billState, orderId, startTime, endTime);
        result.setData(new BillWarpper(billList).warp());
 		result.setCount(page.getTotal());
     	result.setCode(SUCCESS_TIP.getCode());
     	result.setMsg(SUCCESS_TIP.getMessage());
 		return result;
    }

	/**
	 * 导出发票
	 */
	@RequestMapping(value = "/export")
	@ResponseBody
	@Permission
	public Object export(HttpServletResponse response, Integer billType,Integer billState,String orderId,String startTime,String endTime) throws Exception{
		Map<String, Object> params = new HashMap<>(16);
		params.put("billType", billType);
		params.put("billState", billState);
		params.put("orderId", orderId);
		params.put("startTime", endTime);
		params.put("endTime", endTime);
		List<Map<String, Object>> billVoList = billService.selectBillVoList(params);

		List<List<String>> orderData = new ArrayList<List<String>>();
		if (ToolUtil.isNotEmpty(billVoList)) {
			for (Map<String,Object> billMap : billVoList){
				List<String> rowList = new ArrayList<>();
				rowList.add(getString(billMap.get("billTitle")));
				Object bType = billMap.get("billType");
				rowList.add(ToolUtil.isEmpty(bType) ? ""
						: (ToolUtil.toInt(bType) == 0 ? "增值税普通发票"
						: (ToolUtil.toInt(bType) == 1 ? "增值税专用发票" : "")));
				rowList.add(ToolUtil.isEmpty(billMap.get("opererType")) ? ""
						: (ToolUtil.toInt(billMap.get("opererType")) == 0 ? "纸质发票" : ""));
				rowList.add(getString(billMap.get("orderPrice")));
				Object bState = billMap.get("billState");
				rowList.add(ToolUtil.isEmpty(bState) ? ""
						: (ToolUtil.toInt(bState) == 0 ? "未开具"
						: ((ToolUtil.toInt(bState) == 1 || ToolUtil.toInt(bState) == 2) ? "已开具"
						: "已驳回")));
				rowList.add(ToolUtil.isEmpty(billMap.get("createTime")) ? "" : DateUtil.getTime((Date) billMap.get("createTime")));
				rowList.add(getString(billMap.get("orderId")));
				orderData.add(rowList);
			}
		}

		//表名
		String fileName ="发票信息表"+DateUtil.getAllTime();
		// 第六步，将文件存到浏览器设置的下载位置
		String filename = fileName + ".xls";

		response.setContentType("application/ms-excel;charset=UTF-8");
		response.setHeader("Content-Disposition", "attachment;filename="
				.concat(String.valueOf(URLEncoder.encode(filename, "UTF-8"))));
		OutputStream out = response.getOutputStream();
		ExportExcelUtils eeu = new ExportExcelUtils();
		HSSFWorkbook workbook = new HSSFWorkbook();

		String[] header = {"发票抬头", "发票类型", "开具类型", "发票金额", "审核状态", "申请时间", "订单号"};
		Integer sheetNum = 0;
		eeu.exportExcel(workbook, sheetNum, "发票信息", header, orderData, out);
		try {
			// 将数据写出去
			workbook.write(out);
			String str = "导出" + fileName + "成功！";
			System.out.println(str);
		} catch (Exception e) {
			e.printStackTrace();
			String str1 = "导出" + fileName + "失败！";
			System.out.println(str1);
		} finally {
			out.close();
		}
		return SUCCESS_TIP;
	}

	  /**
	   * 跳转到审核发票页面
	   * @param billId
	   * @param model
	   * @return
	   */
	  @RequestMapping(value="/bill_review/{billId}") 
	  public String billReview(@PathVariable Integer billId,Model model) {
		  Map<String, Object> selectBillMap=billService.selectBillReview(billId);
		  List<Map<String,Object>> list=new ArrayList<>();
		  list.add(selectBillMap);
		  Object billList = new BillWarpper(list).warp();
		  model.addAttribute("billList",billList);
		  return PREFIX+"bill_review.html";
	  }
	 
	  /**
	   * 更新发票审核
	   * @param bill
	   * @return
	   */
    @RequestMapping(value="/review")
    @ResponseBody
    @Permission
    public Object billReview(Bill bill) {
    	Order order = orderService.selectById(bill.getOrderId());
    	bill.setUpdateTime(new Date());
    	boolean flag = bill.updateById();
    	if(flag && ToolUtil.isNotEmpty(order)) {
    		if(bill.getBillState() == 2) {
    			ConstantFactory.me().toSendUserMsg("USER_BILL", "您申请的订单号为"+bill.getOrderId()+"的发票已成功开具！", order.getUserId());
    		}
    		if(bill.getBillState() == 3) {
    			ConstantFactory.me().toSendUserMsg("USER_BILL", "由于“"+bill.getRejectReason()+"”，您的发票开具申请未通过，请重新申请！", order.getUserId());
    		}
			
		}
    	return SUCCESS_TIP;
    }
    /**
     * 跳转到发票寄送页面
     * @param userAddressId
     * @param model
     * @return
     */
    @RequestMapping(value="/bill_sent/{userAddressId}")
    public String billSent(@PathVariable Integer userAddressId,Model model) {
    	Address address = addressService.selectById(userAddressId);
    	model.addAttribute("address",address);
    	return PREFIX+"bill_sent.html";
    }
    
    /**
     * 发票寄送更新
     * @param bill
     * @return
     */
    @RequestMapping(value="/sent")
    @ResponseBody
    @Permission
    public Object billSent(Bill bill) {
    	Order order = orderService.selectById(bill.getOrderId());
    	bill.setBillState(1);
    	bill.setUpdateTime(new Date());
    	boolean flag = bill.update(new EntityWrapper<Bill>().eq("address_id",bill.getAddressId()));
    	if(flag && ToolUtil.isNotEmpty(order)) {
    		if(bill.getBillState() == 1) {
    			ConstantFactory.me().toSendUserMsg("USER_BILL", "订单号为"+bill.getOrderId()+"的发票已通过"+bill.getLogisticsCompany()+"寄出, 快递单号为"+bill.getExpressNo()+"，请注意查收！", 
    					order.getUserId());
    		}
		}
    	return SUCCESS_TIP;
    }
    
    @RequestMapping(value="/detail/{billId}/{userAddressId}")
    public String billDetail(@PathVariable Integer billId,@PathVariable Integer userAddressId,Model model) {
    	 Map<String, Object> selectBillMap=billService.selectBillReview(billId);
    	 List<Map<String,Object>> list=new ArrayList<>();
		 list.add(selectBillMap);
		 Object billList = new BillWarpper(list).warp();
		 model.addAttribute("billList",billList);
		 Address address = addressService.selectById(userAddressId);
	     model.addAttribute("address",address);
    	return PREFIX+"bill_detail.html";
    }

	/**
	 * 获取字符串类型数据
	 * @param o object
	 * @return 字符串类型数据
	 */
	private String getString(Object o){
		return ToolUtil.isEmpty(o) ? "" : o.toString();
	}
  
}
